/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-4-14 下午6:52 Created by dwzhang
 */
package com.jade.framework.base.util.encryption;

import java.util.Random;

import org.apache.commons.codec.digest.UnixCrypt;
import org.apache.commons.lang3.StringUtils;

/**
 * 采用Unix加密方法.
 *
 * @author dwzhang
 * @version 1.0 13-4-14 下午6:52
 */
public class UnixEncryption implements Encryption
{
    private static Random randomGen = new Random();
    private static final char[] CHARS = "abcdefghijklmnopqrstuvwxyz".toCharArray();

    synchronized String encrypt(String salt, String password)
    {
        return UnixCrypt.crypt(password, salt);
    }

    /**
     * 加密
     *
     * @param password 密码明文
     * @return 加密后的密文
     */
    public synchronized String encrypt(String password)
    {
        char[] chars = new char[2];
        chars[0] = CHARS[randomGen.nextInt(26)];
        chars[1] = CHARS[randomGen.nextInt(26)];
        return encrypt(new String(chars), password);
    }

    /**
     * 检查密码是否匹配
     *
     * @param password  需要检查的密码明文
     * @param encrypted 密码密文
     */
    public boolean check(String password, String encrypted)
    {
        String encrypt = encrypt(encrypted.substring(0, 2), password);
        return StringUtils.equals(encrypt, encrypted);
    }
}
